<template>
	<view class="article-detail" >
		<scroll-view scroll-y="true" class="scroll-content">
			<!-- 文章标题 -->
			<view class="article-title" >{{article.title}}</view>
			
			<!-- 作者信息 -->
			<view class="article-author">
				<view class="count-wrapper">
					<image src="../../../static/作者 .svg" class="article-author-img"></image>
					<text>{{ article.username }}</text>
				</view>
			</view>
			
			<!-- 发布时间和阅读量 -->
			<view class="article-meta">
				<view class="count-wrapper">
					<text class="article-createTime">{{ article.createTime}}</text>
				    <image src='../../../static/阅读量.svg' class="article-count-img" />
				    <text class="article-count-text">{{ article.count }}</text>
				</view>
			</view>
			
			<!-- 文章封面回显 -->
			<img :src="article.articlePhoto" style="width: 80%; display: block; margin: 0 auto; padding-bottom: 10px;">
			
			<!-- 文章内容 -->
			<rich-text :nodes="article.content" class="richText"></rich-text>
			
			<!-- 文章标签 -->
			<view class="aticle-tags">
				<uni-tag  v-for="item in article.artTag" :inverted="true" :text="item.tagName" type="primary" />			
			</view>
			<view>
				<!-- 评论列表组件 -->
				<comment-vue>
					
				</comment-vue>
			</view>
		</scroll-view>
	</view>
	<!-- 底部固定区域 -->
	<view class="fixed-bottom">
		<view class="actions">
			<!-- 点赞按钮 -->
			<image @click="onLike" :src="Boolean(article.isLike) ? '../../../static/已点赞.svg' : '../../../static/未点赞.svg'" class="action-button" />
			<!-- 收藏按钮 -->
			<image @click="onConllect" :src="Boolean(article.isFavorite) ? '../../../static/已收藏.svg' : '../../../static/未收藏.svg'" class="action-button" />
			<!-- 评论按钮 -->
			<image @click="onComment" src="../../../static/评论.svg" class="action-button" />
		</view>
		<!-- 添加评论的输入框 -->
		<uni-easyinput v-model="newComment" placeholder="写下你的评论..." class="comment-input"></uni-easyinput>
		<!-- <button @click="submitComment" class="submit-comment-button" >提交</button> -->
		<image @click="submitComment" src="../../../static/提交.svg" class="submit-comment-button" />
	</view>
	
	<!-- 付费文章弹窗 -->
	    <view v-if="payConfirm" class="overlay">
	      <view class="popup">
	        <text>此文章为付费文章，购买后查看</text>
			<br>
	        <text class="price">价格: ￥10.00</text> <!-- 添加价格显示 -->
	        <button @click="handleBuy" class="buy-button">购买</button>
	      </view>
	    </view>
		
	<!-- 付费确认弹窗 -->
	    <view v-if="payConfirmOnce" class="overlay">
	      <view class="popup">
	        <text>确认购买吗？</text>
			<br>
	        <text class="price">价格: ￥10.00</text> <!-- 添加价格显示 -->
	        <view class="button-container">
	            <button @click="handleBuyConfirm" class="buy-button">购买</button>
	            <button @click="handleBuyCancel" class="cancel-button">取消</button>
	          </view>
	      </view>
	    </view>
		
	<!-- 付费成功弹窗 -->
	<view v-if="paySuccess" class="overlay">
	  <view class="popup">
	    <text>购买成功！</text>
		<br>
	    <button @click="successConfirm" class="buy-button">确定</button>
	  </view>
	</view>
	
	<view v-if="payFail" class="overlay">
	  <view class="popup">
	    <text>余额不足！</text>
		<br>
	    <button @click="failConfirm" class="buy-button">确定</button>
	  </view>
	</view>
</template>

<script setup>

import { onMounted, ref, computed} from 'vue';
import { selectArticleById,articleOnLike,articleCancelLike,
			articleOnFavorite,articleCancelFavorite,articleVisit,
			doPayConfirm,recordPrepare,recordAdd} from '../api/article';
import { useRoute } from 'vue-router';
import commentVue from '../../analyse/comment/comment.vue';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { stubString } from 'lodash';
// // 定义一个函数来处理跳转评论逻辑
// const onComment = () => {
//   uni.navigateTo({
//     url: '../../../pages/analyse/comment'
//   });
// };

	const article = ref({});
	//付费弹窗
	const payConfirm = ref(false);
	//再次确认付费弹窗
	const payConfirmOnce = ref(false);
	//购买成功弹窗
	const paySuccess = ref(false);
	const payFail = ref(false);
	//定义查询付费文章的相关参数
	let articlePayRecordParam = ref({});
	//定义购买文字前的准备参数
	let recordParam = ref({});
	
	//通过LocalStorage获取登录用户信息
	const userDataString = localStorage.getItem("UserId");
	const visitUserId = ref(null);
	
	const onConllect = async ()=>{
		console.log("收藏用户id:"+visitUserId.value);
		let userId = visitUserId.value;
		article.value.isFavorite = !article.value.isFavorite;
		console.log("收藏状态:"+ article.value.isFavorite + " 文章id:" + article.value.id);
		if(article.value.isFavorite){
			const res =  await articleOnFavorite(article.value.id,userId);
			console.log(res.value);
		}else{
			const res =  await articleCancelFavorite(article.value.id,userId);
			console.log(res.value);
		}
	}
	
	const onLike = async ()=>{
		console.log("点赞用户id:"+visitUserId.value);
		let userId = visitUserId.value;
		article.value.isLike = !article.value.isLike;
		console.log("点赞状态:"+ article.value.isLike + " 文章id:" + article.value.id);
		if(article.value.isLike){
			const res =  await articleOnLike(article.value.id,userId);
			console.log(res.value);
		}else{
			const res =  await articleCancelLike(article.value.id,userId);
			console.log(res.value);
		}
	}
	
	// 购买文字第一次点击事件
	const handleBuy = async ()=> {
		recordParam.value.accountUserId = article.value.userId;
		recordParam.value.articleId = article.value.id;
		recordParam.value.payerUserId = visitUserId.value;
		recordParam.value.transactionAmount = 10;
		updateTime();
		const res = await recordPrepare(recordParam.value);
		if(res.code == 2002){
			console.log(res.data);
			recordParam.value.recordId = res.data;
			payConfirmOnce.value = true;
		}
	}
	
	//确认购买
	const handleBuyConfirm = async ()=> {
		console.log(recordParam.value);
		const res = await recordAdd(recordParam.value);
		console.log(res);
		if(res.data == 4004){
			payFail.value = true;
		}else{
			paySuccess.value = true;
		}
	}
	
	//确认购买弹窗取消
	const handleBuyCancel = ()=> {
		payConfirmOnce.value = false;
		recordParam.value = {};
		console.log(recordParam.value);
	}
	
	const successConfirm = ()=> {
		payFail.value = false;
		paySuccess.value = false;
		payConfirmOnce.value = false;
		payConfirm.value = false;
	}
	
	const failConfirm = ()=> {
		payFail.value = false;
		paySuccess.value = false;
		payConfirmOnce.value = false;
	}
	
	const updateTime = () => {
	  const now = new Date();
	  const year = now.getFullYear();
	  const month = String(now.getMonth() + 1).padStart(2, '0');
	  const day = String(now.getDate()).padStart(2, '0');
	  const hours = String(now.getHours()).padStart(2, '0');
	  const minutes = String(now.getMinutes()).padStart(2, '0');
	  const seconds = String(now.getSeconds()).padStart(2, '0');
	
	  recordParam.value.transactionTime = new Date(`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);
	}
	
	//文章详情页面加载时,从数据库加载文章详情
	onShow(()=>{
		const userData = JSON.parse(userDataString);
		visitUserId.value = userData.data;
		//获取文章信息
		getArticle();
		//判断付费文章是否购买
		payRecordConfirm();
		visit();
	})
	
	const payRecordConfirm = async ()=>{
		articlePayRecordParam.value.userId = visitUserId.value;
		let articleId;
		let route = useRoute();
		articlePayRecordParam.value.articleId = route.query.id;
		const res = await doPayConfirm(articlePayRecordParam.value);
		if(res.data == 0 && article.value.isCharge == 1){
			payConfirm.value = true;
		}else {
			payConfirm.value = false;
		}
		
	}
	
	const getArticle = async ()=>{
		try{
			console.log("当前用户id:"+visitUserId.value);
			let userId = visitUserId.value;
			//通过文章id加载文章 暂定文章id为2
			let articleId;
			//拿取路径中携带的查询参数
			let route = useRoute();
			console.log('从路由中获取到的参数：', route.params); // 获取动态路由参数
			console.log('从路由中获取到的查询参数：', route.query); // 获取URL查询参数
			//将拿取到的查询参数赋值给articleId
			articleId = route.query.id;
			console.log(articleId);
			const res = await selectArticleById(articleId,userId);
			console.log('文章加载结果:',res);
			if(res && res.data){
				article.value = res.data;
				let articlePhoto = article.value.articlePhoto;
				//截取第二个'/'后的内容
				articlePhoto = articlePhoto.substring(article.value.articlePhoto.indexOf('/') + 1);
				articlePhoto = articlePhoto.substring(articlePhoto.indexOf('/'));
				article.value.articlePhoto = 'http://localhost:10002' + articlePhoto;
				console.log(article.value);
			}else {
				console.error('无法加载文章:',res);
			}
		}catch (e){
			console.error('加载文章时发生错误',e);
		}
	}
	
	const visit = async ()=>{
		try{
			//通过文章id加载文章 暂定文章id为2
			let articleId;
			//拿取路径中携带的查询参数
			let route = useRoute();
			console.log('从路由中获取到的参数：', route.params); // 获取动态路由参数
			console.log('从路由中获取到的查询参数：', route.query); // 获取URL查询参数
			//将拿取到的查询参数赋值给articleId
			articleId = route.query.id;
			const res = await articleVisit(articleId);
			console.log(res.value);
		}catch (e){
			console.error('增加阅读量时发生错误',e);
		}
	}
	
</script>

<style scoped>
	
	.article-createTime{
		padding-right: 20rpx;
	}
	
	.article-author,
	.article-meta {
		font-size: 14px;
		color: #666;
		margin-bottom: 8px;
	}
	
	.article-meta {
	  display: flex;
	  align-items: center; /* 垂直居中 */
	}
	
	.count-wrapper {
	  display: flex;
	  align-items: center; /* 确保图片和文字垂直居中 */
	  margin-left: 10px; /* 图片与创建时间之间的间距 */
	}
	
	.article-author-img,
	.article-count-img {
	  width: 20px; /* 设置图片宽度 */
	  height: 20px; /* 设置图片高度 */
	  margin-right: 5px; /* 图片与文字间的间距 */
	}
	
	/* 遮罩层样式 */
	.overlay {
	  position: fixed;
	  top: 0;
	  left: 0;
	  width: 100%;
	  height: 100%;
	  background: rgba(0, 0, 0, 0.5);
	  display: flex;
	  justify-content: center;
	  align-items: center;
	}

	
	.popup {
	  background: white;
	  padding: 20px;
	  border-radius: 8px;
	  text-align: center;
	}
	
	.button-container {
	  display: flex; /* 使用Flexbox布局 */
	  justify-content: space-between; /* 按钮之间有间距 */
	  margin-top: 20px; /* 上边距 */
	}
	
	.price {
	  margin-top: 10px; /* 上边距 */ 
	  font-size: 1.2em; /* 字体大小 */
	  font-weight: bold; /* 字体加粗 */
	  color: #000000; /* 价格颜色 */
	}
	
	.buy-button,
	.cancel-button {
	  padding: 8px 16px; /* 内边距 */
	  font-size: 0.9em; /* 字体大小 */
	  border: none;
	  border-radius: 4px;
	  color: white; /* 按钮文字颜色 */
	  cursor: pointer;
	  flex: 1; /* 使按钮等宽 */
	  margin: 0 5px; /* 按钮之间的间距 */
	}

	.buy-button {
	  background-color: #007BFF; /* 购买按钮背景颜色 */
	}

	.cancel-button {
	  background-color: #666; /* 取消按钮背景颜色 */
	}
	
	.article-detail {
		position: relative;
		background-color: #fff;
		padding: 30rpx 30rpx 160rpx 30rpx;
	}

	.article-title {
		font-size: 28px;
		margin-bottom: 16px;
	}

	

	.fixed-bottom {
		position: fixed;
		height: 80rpx;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		/* padding: 8px 16px; */
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.actions {
		display: flex;
		justify-content: center; /* 水平居中 */
		align-items: center; /* 垂直居中 */
	}

	.action-button {
		margin: 0 8rpx;
		height: 50rpx;
		width: 50rpx;
	}

	.comment-input {
		flex: 1;
		margin-right: 8px;
	}

	.submit-comment-button {
		/* background-color: #007AFF; */
		/* color: #fff; */
		margin: 0 8rpx;
		height: 50rpx;
		width: 50rpx;
	}
	.aticle-tags{
		background-color: #fff;
		padding: 16rpx;
		margin-right: 10rpx;
	}
	
	/* 回显文章内容样式 */
	/* 全局样式 */
	.richText p, .richText span, .richText div {
	  font-size: 18px; /* 设置默认字体大小 */
	  font-family: 'STSong ', sans-serif; /* 设置字体 */
	}
	
	.richText h1, .richText h2, .richText h3, .richText h4, .richText h5, .richText h6 {
	  font-size: 24px; /* 设置标题字体大小 */
	  font-family: 'Microsoft YaHei', sans-serif; /* 设置字体 */
	}
</style>